import React from "react";

import PageContent from '../../PageContent'

import { Link } from 'react-router-dom';

import { ajax ,showResultMessage,isNull,batchAjax, isNotNull,setStoreItem,getStoreItem} from '../../common';

import ConfigProductUIComponentDataSourcePanel from './ConfigProductUIComponentDataSourcePanel';

import {UIDataTableView} from '../../uicomponents/UIDataComponentView';

import UIFormView from '../../uicomponents/UIFormView';

import UIView from '../../uicomponents/UIView';

import UIToolbar from '../../uicomponents/UIToolbar';

import ImportProductUIFormPanel from './ImportUIDataFilePanel';

import ExportProductUIFormPanel from './ExportUIDataFilePanel';

import ImportProductModelPropertiesPanel from './ImportProductModelPropertiesPanel';

/** 
 *产品UI表单管理
*/
export default class ProductUIFormManageApp extends React.Component {

	state = {
		formSearchValues : getStoreItem('uiFormListSearchValues',{}),
	}

	onFormSearchValueChange = (values) => {
		this.setState({formSearchValues : values});
		setStoreItem('uiFormListSearchValues',values)
	}

	render() {

        /**路由设置 */
		const pageContentMap = {
			'/': {
				text: '',
				icon: '',
				getComponent: (owner, props) => {
					return (<ProductUIFormListPanel {...props} 
						formSearchValues={this.state.formSearchValues} 
						onFormSearchValueChange={this.onFormSearchValueChange}
						key="uiFormList" 
						
						/>
						);
				}
			},
			'/editUIFormFields': {
				text: '编辑表单字段',
				icon: 'edit',
				getComponent: (owner, props) => {
					return (<EditProductUIFormFieldListPanel {...props} key="editUIFormFields" />);
				}
			},
			'/importDataFiles': {
				text: '导入UI表单',
				icon: 'sign-in-alt',
                getComponent: (owner, props) => {
                    return <ImportProductUIFormPanel {...props} importURL="PRODUCT/UI/import/importUIFormFile/" pageTitle="导入UI表单" key="importForms"/>;
                }
			},
			'/exportDataFiles': {
				text: '导出UI表单',
				icon: 'sign-out-alt',
                getComponent: (owner, props) => {
                    return <ExportProductUIFormPanel {...props} exportURL="PRODUCT/UI/export/exportUIFormFile/" pageTitle="导出UI表单" key="exportForms"/>;
                }
			},
        }

		return (
			<PageContent {...this.props} pageInstance={this} contentMap={pageContentMap}>
				
			</PageContent>
		);
	}
}

/**
 * 动态列表
 */
class ProductUIFormListPanel extends React.Component {

	constructor(props) {
		super(props);
		this.state = {
			formTitle: '',
			searchValues : props.formSearchValues,
		}
    }

    actionHandler = (actionEvent) => {

		const { selectIds, formListRef, formFormRef } = this;

		return {
			refresh : () => {
				formListRef.loadData();
			},
			addNew : () => {
				this.setState({ formTitle: '新增表单'});
				setTimeout(() => {
					formFormRef.openModal(() => {
						const initParams = getStoreItem('uiFormListSearchValues',{});
						if(isNotNull(initParams['domainId'])){
							formFormRef.setFormData({domainId : initParams['domainId']});
						}
					});
				});
			},
			doEdit : () => {
				this.setState({ formTitle: '编辑表单' });
				setTimeout(() => {
					formFormRef.openModal(() => {
						formFormRef.setFormData(actionEvent.params);
					});
				});
			},
			doDelete : () => {
				let selectedIds = null;

				if (actionEvent.params != null) {
					selectedIds = [actionEvent.params.id];
				}
				else {
					selectedIds = selectIds;
				}

				ajax('PRODUCT/UI/productUIForm/batchDelete', { ids: selectedIds }, (data) => {
					formListRef.loadData();
				});
			},
			doSave : () => {
				formFormRef.getFormData((formData) => {

					ajax('PRODUCT/UI/productUIForm/save', formData, (data) => {
						formFormRef.closeModal();
						formListRef.loadData();
						showResultMessage({
							success: true,
							message: 'message.saveSuccess',
						});
					});
				});
			}
		};
	}

	render() {

		const tableProps = {
			bordered : false,
			history : this.props.history,
			title : "UI表单",
			extra : (<UIToolbar history={this.props.history} actionGroupId="ProductUI:productUIDataPanelActionGroup" actionHandler={this.actionHandler}/>),
			ref: (inst) => { this.formListRef = inst },
			actionHandler: this.actionHandler,
			actionGroupId: 'ProductUI:productUIFormListActionGroup',
			rowActionGroupId: 'ProductUI:productUIFormRowActionGroup',
			tableConfigId: 'ProductUI:productUIFormTable',
			dataUrl: 'PRODUCT/UI/productUIForm/query',
			selectMode: 'multi',
			searchFormId: 'ProductUI:productUIFormSearchForm',
			initSearchValues : this.props.formSearchValues,
			autoLoad: true,
			setToolbarState: (topToolBar, selectedIds) => {
				if (selectedIds.length > 0) {
					topToolBar.enable('delete');
					topToolBar.enable('edit');
				}
				else {
					topToolBar.disable('delete');
					topToolBar.disable('edit');
				}
			},
			onSelectChange:
				(selectRowKeys) => {
					this.selectIds = selectRowKeys;
				}
			,
			onSearchData : (changedValues) => {
				
				if(this.props.onFormSearchValueChange){
					this.props.onFormSearchValueChange(changedValues)
				}
			}
		};

		const formProps = {
			ref: (inst) => { this.formFormRef = inst },
			formConfigId: 'ProductUI:productUIFormForm',
			actionGroupId: 'ProductUI:saveActionGroup',
			actionHandler: this.actionHandler,
			inPop: true,
			destroyOnClose: true,
			title: this.state.formTitle,
		};

		return (
			<UIDataTableView {...tableProps}>
				<UIFormView {...formProps} />
			</UIDataTableView>
		);
	}
}

/**
 * 编辑表单字段
 */
class EditProductUIFormFieldListPanel extends React.Component {

    constructor(props) {
		super(props);
		this.state = {
			formTitle: '',
			pageTitle : '',
			formField : null,
		}
	}
	
	componentDidMount(){
		this.form = this.props.location.state;
		this.setState({pageTitle : '编辑[' + this.form.code +   ']表单字段'});
		this.loadFormFields(this.form.id);
	}

    loadFormFields = (formId) => {
		
        this.formFiledListRef.loadData({formId : formId});
    }

    actionHandler = (actionEvent) => {

		const { selectIds,fieldEditFormRef, formFiledListRef, fieldDataSourceViewRef,fieldDataSourceRef, importModelPropertyViewRef, importModelPropertyRef,fieldBatchEditFormRef,form } = this;

		const {formField} = this.state;

		return {
			refresh : () => {
				formFiledListRef.loadData({formId :form.id});
			},
			addNew : () => {
				this.setState({ formTitle: '添加表单字段',formField : null});
				
				setTimeout(() => {
					fieldEditFormRef.openModal();
				});
			},
			doEdit : () => {
				this.setState({ formTitle: '编辑表单字段',formField : actionEvent.params });
				
				setTimeout(() => {
					fieldEditFormRef.openModal(() => {
						fieldEditFormRef.setFormData(actionEvent.params);
					});
				});
			},
			setFormFieldDataSource : () => {
				this.setState({ formField : actionEvent.params });
				setTimeout(() => {
					fieldDataSourceViewRef.openModal();
				});
				
			},
			doDelete : () => {
				let selectedIds = null;

				if (isNull(actionEvent.params) !== true) {
					selectedIds = [actionEvent.params.id];
				}
				else {
					selectedIds = selectIds;
				}

				ajax('PRODUCT/UI/productUIFormField/batchDelete', { ids: selectedIds }, (data) => {
					formFiledListRef.loadData({formId :form.id});
				});
			},
			importFormFields : () => {
				importModelPropertyViewRef.openModal();
			},
			batchEditProperty : () => {
				fieldBatchEditFormRef.openModal();
			},
			doSave : () => {

				if(fieldEditFormRef.isOpend()){
					fieldEditFormRef.getFormData((formData) => {
						formData.formId = form.id;
						ajax('PRODUCT/UI/productUIFormField/save', formData, (data) => {
							fieldEditFormRef.closeModal();
							formFiledListRef.loadData({formId :form.id});
							showResultMessage({
								success: true,
								message: 'message.saveSuccess',
							});
						});
					});
				}
				else if(fieldDataSourceViewRef.isOpend()){
					
					fieldDataSourceRef.getDataSource((dataSource) => {
						formField.dataSource = isNull(dataSource) ? '' : dataSource.id;
						ajax('PRODUCT/UI/productUIFormField/save',formField,(data) => {
							fieldDataSourceViewRef.closeModal();
							formFiledListRef.loadData({formId :formField.formId});
						});
					});
				}
				else if(importModelPropertyViewRef.isOpend()){
					
					const fields =  importModelPropertyRef.getSelectProperties();
					const urls = [];
					const formFields = fields.map( (field,index) => {
						urls.push('PRODUCT/UI/productUIFormField/save');
						return {
							formId : form.id,
							typeId : 1,
							code : field.property,
							title : field.propertyTitle,
							sortIndex : index + 1,
						}
					} );

					batchAjax(urls, formFields, (data) => {
						importModelPropertyViewRef.closeModal();
						formFiledListRef.loadData({formId : form.id});
						showResultMessage({
							success: true,
							message: 'message.saveSuccess',
						});
					});
				}
				else if(fieldBatchEditFormRef.isOpend){
					fieldBatchEditFormRef.getFormData(formData => {
						
						const editData = {};
						for(let key in formData){
							if(isNotNull(formData[key])){
								editData[key] = formData[key];
							}
						}
						
						const formFiledDataList = formFiledListRef.getSelectedDatas();
						const urls = [];
						const formFields = formFiledDataList.map( (field) => {
							urls.push('PRODUCT/UI/productUIFormField/save');
							return {...field,...editData};
						} );

						batchAjax(urls, formFields, (data) => {
							fieldBatchEditFormRef.closeModal();
							formFiledListRef.loadData({formId : form.id});
							showResultMessage({
								success: true,
								message: 'message.saveSuccess',
							});
						});
					});
				}
			},
			moveDown : () => {
				const rowData = actionEvent.params;
				if(rowData.sortIndex < formFiledListRef.getListData().length){
					rowData.sortIndex = rowData.sortIndex + 1;
					ajax('PRODUCT/UI/productUIFormField/save',rowData,(data) => {
						formFiledListRef.loadData({formId :form.id});
					});
				}
			},
			moveUp : () => {
				const rowData = actionEvent.params;
				if(rowData.sortIndex > 1){
					rowData.sortIndex = rowData.sortIndex - 1;
					ajax('PRODUCT/UI/productUIFormField/save',rowData,(data) => {
						formFiledListRef.loadData({formId :form.id});
					});
				}
			},
			
		};
	}

	render () {

		const {formField} = this.state;

		const tableProps = {
			bordered : false,
			title : this.state.pageTitle,
			ref: (inst) => { this.formFiledListRef = inst },
			actionHandler: this.actionHandler,
			actionGroupId: 'ProductUI:productUIFormFieldListActionGroup',
			rowActionGroupId: 'ProductUI:productUIFormFieldRowActionGroup',
			tableConfigId: 'ProductUI:productUIFormFieldTable',
			dataUrl: 'PRODUCT/UI/productUIFormField/query',
			selectMode: 'multi',
			autoLoad: false,
			setToolbarState: (topToolBar, selectedIds) => {
				if (selectedIds.length > 0) {
					topToolBar.enable('delete');
					topToolBar.enable('batchEditProperty');
				}
				else {
					topToolBar.disable('delete');
					topToolBar.disable('batchEditProperty');
				}
			},
			onSelectChange:
				(selectRowKeys) => {
					this.selectIds = selectRowKeys;
				}
			,
		};

		return (
			<UIDataTableView extra={<Link to="/">返回</Link>} {...tableProps}>
				<UIFormView formConfigId="ProductUI:productUIFormFieldForm" 
					inPop={true} destroyOnClose={true} title={this.state.formTitle} ref={(inst) => this.fieldEditFormRef = inst} 
					 actionGroupId={'ProductUI:saveActionGroup'} actionHandler={this.actionHandler}
					/>
				<UIFormView formConfigId="ProductUI:productUIFormFieldBatchEditForm"
					inPop={true} destroyOnClose={true} title="批量设置属性" ref={(inst) => this.fieldBatchEditFormRef = inst} 
					 actionGroupId={'ProductUI:saveActionGroup'} actionHandler={this.actionHandler}
					/>
				<UIView width={1000} inPop={true} destroyOnClose={true} title="设置数据源" ref={(inst) => this.fieldDataSourceViewRef = inst}
					bordered={false} actionGroupId={'ProductUI:saveActionGroup'}
					actionHandler={this.actionHandler}>
					<ConfigProductUIComponentDataSourcePanel  datasourceId={isNull(formField) ? '' : formField.dataSource} ref={(inst) => this.fieldDataSourceRef = inst}/>
				</UIView>
				<UIView width={600} inPop={true} destroyOnClose={true} title="导入对象属性" ref={(inst) => this.importModelPropertyViewRef = inst}
					bordered={false} actionGroupId={'ProductUI:saveActionGroup'}
					actionHandler={this.actionHandler}>
					<ImportProductModelPropertiesPanel ref={(inst) => this.importModelPropertyRef = inst}/>
				</UIView>
			</UIDataTableView>
		);
	}
}


